import querystring from '@src/util/querystring2'
import { defineComponent, computed, onMounted, ref } from 'vue';
import { connectorAddOnsFieldList, connectorSaveAddOnsFieldList } from '@src/api/ConnectorApi';
import Form from './components/Form.vue'
import '@src/modules/add-ons/style/home.scss'
import Field from '@model/entity/Field';
import { ConnectorToField } from '@src/modules/connector';
import { message } from '@src/util/message'


export default defineComponent({
  setup() {
    const formFields = ref<Field []>([])
    const buttonDisabled = ref(false)
    const formRef = ref(null)
    const urlParams = computed<Record<string, any>>(() => {
      const searchParams = window.location.search || '';
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      const searchParamsObj = querystring.parseParams(searchParams);
      return searchParamsObj || {};
    });


    /**
     * 相关连接器字段转为表单的field字段
     * @param {any} fields=[]
     * @returns {any}
     */
    const convertConnectorFieldToFormFields = (fields = []) :Field[]=> {
      return fields.map((item: ConnectorToField)=> {
        const {fieldType, enName, cnName, required, setting } = item
        return {
          fieldName: enName,
          formType: fieldType,
          displayName: cnName,
          isNull: required ? 0 : 1,
          setting
        } as unknown as Field
      })
    }

    const deleteObjectKeys = (object: Record<string, any>, keys: string [] = []) => {
      keys.forEach((item: string)=> {
        Reflect.deleteProperty(object, item)
      })  
    }

    const fetchFields = async ()=> {
      const { bizType, cardId } = urlParams.value
      const { data = [] } = await connectorAddOnsFieldList({bizType, cardId})
      formFields.value = convertConnectorFieldToFormFields(data)
    }

    const handleSubmit = async (params: Record<string, any>) => {
      buttonDisabled.value = true
      deleteObjectKeys(params, ['connectorSourceOperate', 'isCreate', 'processId'])
      const { success = false, message: msg = '' } = await connectorSaveAddOnsFieldList(params).finally(()=> {
        buttonDisabled.value = false
      })

      if(success) {
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        formRef?.value?.handleClose()
      } else {
        message.warning(msg)
      }
    }


    onMounted(()=> {
      fetchFields()
    })
    return () => (
      <div class="add-ons-container">
        <Form ref={formRef} fields={formFields.value} buttonDisabled={buttonDisabled.value} onSubmit={handleSubmit}></Form>
      </div>
    );
  },
});
